<template>
  <div class="video-container">
    <div class="hk-video" ref="hkVideoRef" :id="divId"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, onBeforeUnmount } from "vue";
import { g_iWndIndex } from "./errorCode.js";

const props = defineProps({
  divId: String,
  ip: String,
  port: String,
  username: String,
  password: String,
  channelID: Number,
});

const hkVideoRef = ref(null);

// 设备标识
const szDeviceIdentify = props.ip + "_" + props.port;

function initPlugin() {
  WebVideoCtrl.I_InitPlugin({
    bWndFull: true, // 单窗口双击全屏
    iWndowType: 1, // 分屏类型，默认值为 1，表示单画面
    bDebugMode: false, // JS 调试模式
    cbSelWnd: function (xmlDoc) {},
    cbDoubleClickWnd: function (iWndIndex, bFullScreen) {},
    cbEvent: function (iEventType, iParam1, iParam2) {},
    // 插件初始化完成回调（必须定义）
    cbInitPluginComplete: function () {
      // 插入播放插件
      WebVideoCtrl.I_InsertOBJECTPlugin(props.divId).then(
        () => {
          // 检查插件是否最新
          WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
            if (bFlag) {
              alert(
                "检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！"
              );
            } else {
              loginDevice();
            }
          });
        },
        () => {
          alert(
            "插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！"
          );
        }
      );
    },
  });
}

async function loginDevice() {
  const result = await WebVideoCtrl.I_Login(
    props.ip,
    1, // 1 表示 http 协议，2 表示 https 协议
    props.port,
    props.username,
    props.password,
    {
      timeout: 3000,
      success: function (xmlDoc) {
        console.log("登录成功！设备标识：", szDeviceIdentify);
        //   getDevicePort();

        // setTimeout(() => {
        //   console.log("开始预览。。。");
        //   startRealPlay(channelID);
        // }, 300);
      },
      error: function (error) {
        console.log("登录失败，原因：", error);
      },
    }
  );

  console.log("登录结果：", result);
}

// 退出登录
async function logout() {
  if (null == szDeviceIdentify) {
    return;
  }

  try {
    await WebVideoCtrl.I_Logout(szDeviceIdentify);
    console.log(`退出成功！设备标识 ${szDeviceIdentify}`);
  } catch (error) {
    console.log(`退出失败！设备标识 ${szDeviceIdentify}`);
  }
}

// 销毁播放插件
async function destroyPlugin() {
  try {
    await WebVideoCtrl.I_DestroyPlugin();
    console.log(`销毁插件成功！`);
  } catch (error) {
    console.log(`销毁插件失败！`);
  }
}

// 预览
const startRealPlay = (channelID) => {
  let oWndInfo = WebVideoCtrl.I_GetWindowStatus(g_iWndIndex);

  const startRealPlay = function () {
    WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
      iStreamType: 1,
      iChannelID: channelID,
      bZeroChannel: false,
      success: function () {
        console.log(`设备标识：${szDeviceIdentify}`);
      },
      error: function (oError) {
        console.log(
          szDeviceIdentify + " 开始预览失败！",
          oError.errorCode,
          oError.errorMsg
        );
      },
    });
  };

  if (oWndInfo != null) {
    // 已经在播放了，先停止
    WebVideoCtrl.I_Stop({
      success: function () {
        startRealPlay();
      },
    });
  } else {
    startRealPlay();
  }
};

onBeforeUnmount(async () => {
  await logout();
  await destroyPlugin();
});

onMounted(() => {
  initPlugin();
});
</script>

<script>
export default {
  name: "HkVideo",
};
</script>

<style scoped>
.video-container {
  width: 400px;
  height: 400px;
}
</style>
